<template>
  <div class="main">
    <div class="login-container">
      <el-card class="login-card">
        <h3 class="login-title">用户登录</h3>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码名" prop="password">
            <el-input type="password" v-model="loginForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
          </el-form-item>
          <p @click="regFn" class="regFn">没有账号？请注册</p>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { loginApi } from "../utils/api";

export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: "用户名只能包含数字或数字字母组合，不能有中文",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          loginApi({
            username: this.loginForm.username,
            password: this.loginForm.password,
          }).then((res) => {
            if (res.code === 200) {
              const { token, username,nickname, id } = res.data.data;
              console.log( token, username,nickname, id)

              localStorage.setItem("token", token);
              localStorage.setItem("username", username);
              localStorage.setItem("nickname",nickname);
              localStorage.setItem("id", id);

              // 提示登录成功
              this.$message({
                message: "登录成功",
                type: "success",
                duration: 1000,
              });
              this.$router.push({ path: "/" });
            } else {
              this.$message({
                message: "登录失败",
                type: "error",
                duration: 1000,
              });
            }
          });
        }
      });
    },
    regFn() {
      this.$router.push({ path: "/register" });
    },
  },
};
</script>

<style scoped>
.main {
  background: pink;
  background-image: url("../assets/bglogin.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
  padding: 20px;
  height: 260px;
}

.login-title {
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
}
.regFn {
  color: #409eff;
  cursor: pointer;
}
</style>
